package com.atguigu.gmall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.atguigu.gmall.common.bean.UserInfo;
import com.atguigu.gmall.common.exception.OrderException;
import com.atguigu.gmall.oms.entity.OrderEntity;
import com.atguigu.gmall.payment.config.AlipayTemplate;
import com.atguigu.gmall.payment.interceptors.LoginInterceptor;
import com.atguigu.gmall.payment.pojo.PayAsyncVo;
import com.atguigu.gmall.payment.pojo.PayVo;
import com.atguigu.gmall.payment.pojo.PaymentInfoEntity;
import com.atguigu.gmall.payment.service.PaymentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;

@Controller
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private AlipayTemplate alipayTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("pay.html")
    public String paySelect(@RequestParam("orderToken")String orderToken, Model model){

        // 查询订单
        OrderEntity orderEntity = this.paymentService.queryOrderByToken(orderToken);
        if (orderEntity == null){
            throw new OrderException("非法参数");
        }

        // 判断是否时我的订单
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        Long userId = userInfo.getUserId();
        if (userId != orderEntity.getUserId()){
            throw new OrderException("当前订单不属于您");
        }

        // 判断订单转台
        if (orderEntity.getStatus() != 0) {
            throw new OrderException("当前订单不能支付");
        }

        model.addAttribute("orderEntity", orderEntity);

        return "pay";
    }

    @GetMapping("alipay.html")
    @ResponseBody // 如果controller方法上有该注解，代表当前方法的返回值，以其他视图形式展示
    public String toAlipay(@RequestParam("orderToken")String orderToken){
        // 查询订单
        OrderEntity orderEntity = this.paymentService.queryOrderByToken(orderToken);
        if (orderEntity == null){
            throw new OrderException("非法参数");
        }

        // 判断是否时我的订单
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        Long userId = userInfo.getUserId();
        if (userId != orderEntity.getUserId()){
            throw new OrderException("当前订单不属于您");
        }

        // 判断订单转台
        if (orderEntity.getStatus() != 0) {
            throw new OrderException("当前订单不能支付");
        }

        try {
            // 调用支付宝的支付接口
            PayVo payVo = new PayVo();
            payVo.setOut_trade_no(orderEntity.getOrderSn());
            // 此处一定写成0.01，不要使用订单中的金额
            payVo.setTotal_amount("0.01");
            payVo.setSubject("谷粒商城支付平台");

            // 记录对账信息
            Long payId = this.paymentService.savePaymentInfo(payVo);
            payVo.setPassback_params(payId.toString());

            return this.alipayTemplate.pay(payVo);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    @GetMapping("pay/success")
    public String paySuccess(){
        // TODO: 自己完成
        return "paysuccess";
    }

    @PostMapping("pay/ok")
    @ResponseBody
    public Object payOk(PayAsyncVo payAsyncVo){
        // 验签：确认是否时支付宝发送的
        Boolean flag = this.alipayTemplate.checkSignature(payAsyncVo);
        if (!flag){
            return "failure";
        }

        // 核对订单的业务参数：app_id、out_trade_no、total_amount
        String appId = payAsyncVo.getApp_id();
        String out_trade_no = payAsyncVo.getOut_trade_no();
        String total_amount = payAsyncVo.getTotal_amount();
        // 根据passback_params获取对账记录id，查询对账记录
        String payId = payAsyncVo.getPassback_params();
        PaymentInfoEntity paymentInfoEntity = this.paymentService.queryPaymentInfoById(payId);
        if (!StringUtils.equals(appId, alipayTemplate.getApp_id()) ||
                !StringUtils.equals(out_trade_no, paymentInfoEntity.getOutTradeNo()) ||
                new BigDecimal(total_amount).compareTo(paymentInfoEntity.getTotalAmount()) != 0
        ){
            return "failure";
        }

        // 校验支付状态：TRADE_SUCCESS
        String trade_status = payAsyncVo.getTrade_status();
        if (!StringUtils.equals("TRADE_SUCCESS", trade_status)){
            return "failure";
        }

        // 修改对账记录中的支付状态
        if (this.paymentService.updatePaymentInfo(payAsyncVo) == 1) {
            // 发送消息给oms，标记为待发货状态
            this.rabbitTemplate.convertAndSend("ORDER_EXCHANGE", "order.pay", out_trade_no);
        }

        // 响应数据给支付宝
        return "success";
    }
}
